<%@page import="com.liferay.portal.kernel.util.ParamUtil"%>
<%@page import="com.mad.bikepony.model.Delivery"%>
<%@page import="com.mad.bikepony.model.DeliveryState"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
<%@ taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet"%>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme"%>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui"%>
<%@ taglib uri="http://liferay.com/tld/util" prefix="liferay-util"%>
<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui"%>
<portlet:defineObjects />
<liferay-theme:defineObjects />

<%
String trackingCode = ParamUtil.getString(renderRequest, "tracking_code","");
%>

<liferay-ui:error key="error_new_parcel_request" />
<style type="text/css">
.trackingCode {
	width: 260px;
}
#map-canvas
{
	width: 600px;
	height: 600px;
}
</style>
<script type="text/javascript">
jQuery(document).ready(function(){
	jQuery(".delivery_sig_fieldset").hide();
	jQuery(".tracking_info_fieldset").css("display","block");
	<%if(!trackingCode.equals("")){%>
		searchTrackingCode();
	
	<%}%>
	
	
	
});
var map;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();

	function initialize(latLng)
	{
		var mapOptions = {
		       center: latLng,
		       zoom: 16,
		       mapTypeId: google.maps.MapTypeId.ROADMAP
		     };
		
		map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
    }
	/*
    google.maps.event.addDomListener(window, 'load', initialize);
    */
	function searchTrackingCode()
	{
    	jQuery("#sig-image").html("");
    	 jQuery(".delivery_sig_fieldset").hide();
		var trackingCode = jQuery("#<portlet:namespace/>tracking_code").val();
		if(trackingCode == "")
		{
			jQuery("#message").html("please insert a valid tracking code");
			jQuery("#message").show();
			return;
		}else
			jQuery("#message").hide();
		
		var searchTrackingCodeUrl ="/BikePony-portlet/api/jsonws/delivery/search-by-trackingcode"; 
		jQuery.ajax({
			type:'GET',
			url:searchTrackingCodeUrl,
			dataType:'json',
			data:{
				trackingCode:trackingCode
			},
			success:function(data)
			{
				if(data)
				{
					
					if(data.statusCode==0)
					{
						
						var statusCode = data.data.stateCode;
				        var contentString="<br/><br/>State : <b>"+data.data.stateDescription+"</b><br/>";
				       
						if(statusCode==<%=DeliveryState.WAITING_FOR_PICKUP.toState()%>)
						{
							var date = new Date(data.data.estimatedPickupTime);
							contentString+="<span>Estimated pickup time: </span> <b>"+date.getDate()+"/"+date.getMonth()+"/"+date.getFullYear()+" "+date.getHours()+":"+date.getMinutes()+"</b>";
							
						}else if(statusCode == <%=DeliveryState.BEING_DELIVERED.toState()%>)
						{
							var pickupDate = new Date(data.data.pickupTimestamp);
							var estimatedDeliveryTime = new Date(data.data.estimatedDeliveryTime);
							contentString+="<span>Picked-up on:</span><b> "+pickupDate.getDate()+"/"+pickupDate.getMonth()+"/"+pickupDate.getFullYear()+" "+pickupDate.getHours()+":"+pickupDate.getMinutes()+"</b><br/>";
							contentString+="<span>Estimated pickup time: </span> <b>"+estimatedDeliveryTime.getDate()+"/"+estimatedDeliveryTime.getMonth()+"/"+estimatedDeliveryTime.getFullYear()+" "+estimatedDeliveryTime.getHours()+":"+estimatedDeliveryTime.getMinutes()+"</b>";
							
						}
						else if(statusCode == <%=DeliveryState.DELIVERED.toState()%>)
						{
							var deliveryDate = new Date(data.data.deliveryTimestamp);
							var pickupDate = new Date(data.data.pickupTimestamp);
							contentString+="<span>Picked-up on:</span><b> "+pickupDate.getDate()+"/"+pickupDate.getMonth()+"/"+pickupDate.getFullYear()+" "+pickupDate.getHours()+":"+pickupDate.getMinutes()+"</b><br/>";
							contentString+="<span>Delivered on :</span><b>"+deliveryDate.getDate()+"/"+deliveryDate.getMonth()+"/"+deliveryDate.getFullYear()+" "+deliveryDate.getHours()+":"+deliveryDate.getMinutes()+"</b>";
							jQuery(".delivery_sig_fieldset").show();
							jQuery("#sig-image").html("</br><img style='width: 400px' src='data:image/jpeg;base64,"+data.data.signature+"' />");
						}else
						{
							alert("error: invalid delivery state");
						}
						
						if(data.data.parcelLon && data.data.parcelLat)
						{
							/* myLatLng = new google.maps.LatLng(data.data.parcelLat, data.data.parcelLon);*/
							 codeLatLng(data.data.parcelLat, data.data.parcelLon,contentString);
						}else if(data.data.address)
						{
							codeAddress(data.data.address,contentString);
						}
						jQuery("#<portlet:namespace/>delivery").show();
					}else
					{
						alert("error : "+data.message);
					}
				}
				 
			},error:function(status,error,message)
			{
				alert("an error occurred during tracking code search : "+status+"\n"+error+"\n"+message);
			}
			
		});
	};
	function codeLatLng(lat,lng,content) {
		  var latlng = new google.maps.LatLng(lat, lng);
		  geocoder.geocode({'latLng': latlng}, function(results, status) {
		    if (status == google.maps.GeocoderStatus.OK) {
		      if (results[1]) {
		    	  initialize(latlng);
		    	  map.setZoom(16);
			        marker = new google.maps.Marker({
			            position: results[0].geometry.location,
			            map: map,
			            animation: google.maps.Animation.DROP
			        });
		        infowindow.setContent("your parcel is now in :<br/><br/>"+results[0].formatted_address+"<br>"+content);
		        infowindow.open(map, marker);
		        map.setCenter(latlng);
		      } else {
		        alert('No results found');
		      }
		    } else {
		      alert('Geocoder failed due to: ' + status);
		    }
		  });
		}
	
	function codeAddress(address,content) {
		  geocoder.geocode( { 'address': address}, function(results, status) {
		    if (status == google.maps.GeocoderStatus.OK) 
		    {
		    	initialize(results[0].geometry.location);
		    	map.setZoom(16);
		        marker = new google.maps.Marker({
		            position: results[0].geometry.location,
		            map: map,
		            animation: google.maps.Animation.DROP
		        });
		        infowindow.setContent("your parcel is now in :<br/><br/>"+address+"<br/>"+content);
		        infowindow.open(map, marker);
		        map.setCenter(results[0].geometry.location);
		    } else {
		     alert("the actual position cannot be shown");
		    }
		  });
		}

</script>
<div>
	<div>
	<div class="portlet-msg-info">search for a tracking code . This feature allows you to know which is the status of your parcel</div>
	<div class="portlet-msg-alert" style="display:none;" id="message"></div>
	<aui:input name="tracking_code" label="tracking code" cssClass="trackingCode" inputCssClass="trackingCode" value="<%=trackingCode %>"/>
	<button name="search" onclick="searchTrackingCode()">search</button>
	<br />
	<br />
	<br />
	<table>
		<colgroup>
			<col width="45%"/>
			<col width="10%"/>
			<col width="45%"/>
		</colgroup>
		<tr>
			<td>
				<aui:fieldset label="tracking info" cssClass="tracking_info_fieldset">
					<div id="map-canvas"></div>
				</aui:fieldset>
			</td>
			<td></td>
			<td>
				<aui:fieldset label="delivery signature image" cssClass="delivery_sig_fieldset">
					<div id="sig-image"></div>
				</aui:fieldset>
			</td>
		</tr>
	</table>
	</div>
</div>
